package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

type User struct {
	Id       string `json:"id"`
	Username string `json:"username"`
	Password string `json:"password"`
}

func main() {
	var router = gin.Default()
	router.GET("/getValue", func(c *gin.Context) {
		var username = c.Query("username")
		var password = c.Query("password")
		var user = User{
			Id:       "1",
			Username: username,
			Password: password,
		}
		c.JSON(http.StatusOK, user)
	})
	router.POST("addUser", func(ctx *gin.Context) {
		username := ctx.PostForm("username")
		password := ctx.PostForm("password")
		age := ctx.DefaultPostForm("age", "20")
		ctx.JSON(http.StatusOK, gin.H{
			"username": username,
			"password": password,
			"age":      age,
		})
	})

	router.POST("addUserBody", func(ctx *gin.Context) {
		var user User
		err := ctx.ShouldBindJSON(&user)
		if err != nil {
			ctx.JSON(http.StatusBadRequest, gin.H{
				"error": err.Error(),
			})
			return
		}
		ctx.JSON(http.StatusOK, user)
	})

	router.GET("/userinfo/:uid", func(ctx *gin.Context) {
		uid := ctx.Param("uid")
		ctx.JSON(http.StatusOK, gin.H{
			"uid": uid,
		})
	})

	// post能用路径变量吗？也可以的
	router.POST("/postuserinfo/:uid", func(ctx *gin.Context) {
		uid := ctx.Param("uid")
		ctx.JSON(http.StatusOK, gin.H{
			"uid": uid,
		})
	})

	router.Run(":9000")
}
